var gulp = require('gulp'),
    del = require('del'),
    less = require('gulp-less'),
    uglify = require('gulp-uglify'),
    fileinclude = require('gulp-file-include'),
    browserSync = require('browser-sync').create(),
    reload = browserSync.reload;


// 清除 dist 文件夹
gulp.task('clean', function () {
  return del.sync('./dist');
});

// 编译less文件
gulp.task('testLess', function () {
  return [
    // 生成通用样式css文件
    gulp
      .src('./app/src/less/style.less')
      .pipe(less())
      .pipe(gulp.dest('./dist/css'))
      .pipe(reload({ stream: true })),
    // 生成首页样式css文件
    gulp
      .src('./app/src/less/index/index.less')
      .pipe(less())
      .pipe(gulp.dest('./dist/css'))
      .pipe(reload({ stream: true })),
    // 生成登录css文件
    gulp
      .src('./app/src/less/login.less')
      .pipe(less())
      .pipe(gulp.dest('./dist/css'))
      .pipe(reload({ stream: true })),
    // 注册登录css文件
    gulp
      .src('./app/src/less/register.less')
      .pipe(less())
      .pipe(gulp.dest('./dist/css'))
      .pipe(reload({ stream: true }))
  ];
});

// 压缩js文件
gulp.task('jsmin', function () {
  return gulp
    .src('./app/src/js/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('./dist/js'));
});

// html 整合
gulp.task('html', function () {
  return gulp
    .src('./app/src/template/*.html')
    .pipe(fileinclude())
    .pipe(gulp.dest('./dist'));
});

// 复制图片文件
gulp.task('copy_img', function(){
  return gulp
    .src('./app/src/images/**/*')
    .pipe(gulp.dest('./dist/images'))
});

// 复制css文件
gulp.task('copy_css', function () {
  return gulp
    .src('./app/src/css/**/*')
    .pipe(gulp.dest('./dist/css'))
});

// 复制font文件
gulp.task('copy_font', function () {
  return gulp
    .src('./app/src/fonts/**/*')
    .pipe(gulp.dest('./dist/fonts'))
});

// 配置服务器
gulp.task('serve', function () {
  browserSync.init({
    server: {
      baseDir: './dist'
    },
    port: 8000
  });
  // 监听 html
  gulp.watch('./app/src/template/**/*.html', ['html'])
    .on('change', reload);
  // 监听less
  gulp.watch('./app/src/less/**/*.less', ['testLess'])
    .on('change', reload);
  // 监听 js
  gulp.watch('./app/src/js/**/*.js', ['jsmin'])
    .on('change', reload);
});

gulp.task('default', ['clean', 'testLess', 'jsmin', 'html', 'copy_css', 'copy_img', 'copy_font', 'serve']);
